package com.cloudtcm.serviece.impl;

import com.cloudtcm.constant.MessageConstant;
import com.cloudtcm.constant.StatusConstant;
import com.cloudtcm.dto.DockerLoginDTO;
import com.cloudtcm.dto.DockerDTO;
import com.cloudtcm.entity.Docker;
import com.cloudtcm.exception.AccountNotFoundException;
import com.cloudtcm.exception.PasswordErrorException;
import com.cloudtcm.mapper.DockerMapper;
import com.cloudtcm.serviece.DockerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class DockerServiceImpl implements DockerService {
    @Autowired
    private DockerMapper dockerMapper;
    @Override
    public Docker login(DockerLoginDTO dockerLoginDTO) {
        String username = dockerLoginDTO.getUsername();
        String password = dockerLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Docker docker = dockerMapper.getByUsername(username);


        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (docker == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传出的明文md5密码加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(docker.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //3、返回实体对象
        return docker;
    }

    /**
     * 医生注册
     * @param dockerDTO
     */
    @Override
    public void save(DockerDTO dockerDTO) {
        Docker docker = Docker.builder()
                .username(dockerDTO.getUsername())
                .name(dockerDTO.getName())
                .password(DigestUtils.md5DigestAsHex(dockerDTO.getPassword().getBytes()))
                .phone(dockerDTO.getPhone())
                .sex(dockerDTO.getSex())
                .createTime(LocalDateTime.now())
                .direction(dockerDTO.getDirection())
                .grade(dockerDTO.getGrade())
                .image(dockerDTO.getImage())
                .prove_image(dockerDTO.getProve_image())
                .status(StatusConstant.DISABLE)
                .comment(dockerDTO.getComment())
                .build();
        dockerMapper.insert(docker);
    }

    /**
     * 更新医生信息
     * @param dockerDTO
     */
    @Override
    public void update(DockerDTO dockerDTO) {
        Docker docker = new Docker();
        BeanUtils.copyProperties(dockerDTO,docker);
        docker.setPassword(DigestUtils.md5DigestAsHex(dockerDTO.getPassword().getBytes()));
        if(docker.getProve_image()!=null) docker.setStatus(StatusConstant.DISABLE);
        dockerMapper.update(docker);
    }
}
